package com.mng.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mng.controller.util.R;
import com.mng.domain.Book;
import com.mng.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    public BookService bookService;

    @GetMapping
    public R getAll(){
        List<Book> bookList = bookService.getAll();
        return new R(true,bookList);
    }
    @PostMapping
    public R insertBook(@RequestBody Book book) throws IOException{
        if (book.getName().equals("123") ) throw new IOException();
        Boolean flag = bookService.save(book);
        return new R(flag,flag ? "添加成功" : "添加失败");
    }
    @PutMapping
    public R update(@RequestBody Book book) throws IOException {
        if (book.getName().equals("123") ) throw new IOException();
        boolean flag = bookService.update(book);
        return new R(flag, flag ? "修改成功" : "修改失败");
    }
    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id){
        return new R(bookService.delete(id));
    }

    @GetMapping("{id}")
    public R getById(@PathVariable Integer id){
        return new R(true, bookService.getById(id));
    }
    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable Integer currentPage, @PathVariable Integer pageSize,Book book){
        IPage<Book> page = bookService.getPage(currentPage, pageSize,book);
        //如果当前页码值大于了总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
        if(currentPage > page.getPages()){
            page = bookService.getPage(currentPage, pageSize,book);
        }
        return new R(true,page);
    }

}
